.data
	x: .long 0			# input x for function
	sum: .long 0			# summary of all measured values
	str: .string "%d\n Rest %d\n"	# result for measured values in f(x)

.text
.globl main
main:
	movl $0, %edi			# index j starts with 0
	movl $0, %ebx			# sum starts with 0

.L1:
	cmpl $9, %edi			# while index != 10
	movl $0, %ecx
	je .L2				# i == 10 go to L2
	
	pushl $x			# push x into stack
	pushl $str			# push string into stack
	call scanf			# call scan
	addl $8, %esp			# fill stackpointer

	movl x, %eax			# move x into %eax reg
	pushl %eax			# push %eax into stack
	call fx				# call function f(x) = x^2 + 2x - 2

	addl %eax, %ebx			# add result into sum		

	addl $1, %edi			# iteration i + 1
	jmp .L1				# go to L1 again

.L2:
	movl $10, %eax			# move 10 into %eax (measured values)
	cmpl %eax, %ebx			# if %ebx(sum) < %eax(10)
	jl .L3				# if true, go to L3
	subl %eax, %ebx			# else sum - measured values
	addl $1, %ecx			# %ecx + 1 (ecx * 10 == sum)
	jmp .L2				# go to L2 again

.L3:
	pushl %ebx
	pushl %ecx			# push %eax into stack
	pushl $str			# push output string into stack
	call printf			# call print
	addl $8, %esp			# fill stackpointer
	
	movl $1, %eax			# exit
	int $0x80			# software interrupt

.globl fx
fx:
	pushl %ebp			# push basepointer
	movl %esp, %ebp			# move stackpointer into basepointer
	pushl %ebx			# push %ebx(sum) into stack

	movl 8(%ebp), %eax		# move x into %eax

	movl x, %ebx			# move x into %ebx reg
	imull %eax			# x * x
	pushl %eax			# push %eax (x * x) into stack
	movl x, %eax			# move x into %eax reg
	movl $2, %ebx			# move 2 into %ebx reg
	imull %ebx			# 2 * x
	xchgl %eax, %ebx		# change value in regs
	popl %eax			# pop %eax (x * x)
	addl %ebx, %eax			# (x * x) + (2 * x)
	subl $2, %eax			# (x * x) + (2 * x) - 2

	movl %eax, 8(%ebp)		# move %ebx into basepointer
	popl %ebx			# pop %ebx (sum) into stack
        popl %ebp			# pop basepointer
	ret